﻿Imports System.ServiceModel
Imports PowerShellCron.ServiceContract

Public Class PSCProxy
    Implements IDisposable

    Private _channel As IManageSvc
    Private Shared channelFactory As ChannelFactory(Of IManageSvc)

    Private ReadOnly Property Channel As IManageSvc
        Get
            Return Me._channel
        End Get
    End Property

    Public Sub New(serverName As String, port As Integer, upn As String)
        Dim uri As String = String.Format("net.tcp://{0}:{1}/PowerShellCron", serverName, port)
        If channelFactory Is Nothing Then
            channelFactory = New ChannelFactory(Of IManageSvc)(New NetTcpBinding, New EndpointAddress(New Uri(uri), EndpointIdentity.CreateUpnIdentity(upn)))
        End If
        Me._channel = channelFactory.CreateChannel()
        DirectCast(Me._channel, Channels.IChannel).Open()
    End Sub

#Region "IDisposable Support"
    Private disposedValue As Boolean ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: dispose managed state (managed objects).
                If Me.Channel IsNot Nothing Then
                    Try
                        If DirectCast(Me._channel, Channels.IChannel).State = CommunicationState.Opened Then
                            DirectCast(Me._channel, Channels.IChannel).Close()
                        End If
                    Catch ex As Exception
                        DirectCast(Me._channel, Channels.IChannel).Abort()
                        If Not TypeOf ex Is CommunicationException AndAlso Not TypeOf ex Is TimeoutException Then
                            Me.disposedValue = True
                            Throw
                        End If
                    End Try
                End If
            End If

            ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
            ' TODO: set large fields to null.
        End If
        Me.disposedValue = True
    End Sub

    ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
    'Protected Overrides Sub Finalize()
    '    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    '    Dispose(False)
    '    MyBase.Finalize()
    'End Sub

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class
